﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Innovator
{
	public class GameScreen
	{
		public ComponentCollection Components;
		public bool Visible = true;
		public bool BlocksUpdate = false;
		public bool OverrideUpdateBlocked = false;
		public bool BlocksDraw = false;
		public bool OverrideDrawBlocked = false;
		public bool BlocksInput = false;
		public bool OverrideInputBlocked = false;
		public bool InputDisabled = false;
		public bool IsInputAllowed = true;
		public string Name;
		public event EventHandler OnInitialized;
		bool initialized = false;
		public bool Initialized 
		{
			get { return initialized; }
			set
			{
				initialized = value;
				if (OnInitialized != null)
				{
					OnInitialized(this, new EventArgs());
				}
			}
		}
		public GameScreen(string Name)
		{
			Components = new ComponentCollection(this);
			this.Name = Name;
			Engine.GameScreens.Add(this);
			if (!initialized)
				Initialize();
		}
		public virtual void Initialize()
		{
			this.Initialized = true;
		}
		public virtual void Update()
		{
			List<Component> updating = new List<Component>();
			foreach (Component c in Components)
				updating.Add(c);
			foreach (Component component in updating)
				if (component.Initialized)
					component.Update();
		}
		public virtual void Draw(ComponentType RenderType)
		{
			List<Component> drawing = new List<Component>();
			foreach (Component component in Components.InDrawOrder)
			{
				if (RenderType == ComponentType.Both)
				{
					if (component is I2DComponent || component is I3DComponent)
						drawing.Add(component);
				}
				else if(RenderType == ComponentType.Component2D)
				{
					if (component is I2DComponent)
						drawing.Add(component);
				}
				else if(RenderType == ComponentType.Component3D)
				{
					if (component is I3DComponent)
						drawing.Add(component);
				}
				else
				{
					drawing.Add(component);
				}
			}
			//keep list of 2d SortedDictionary that we can draw them on top of 3D
			List<Component> defer2D = new List<Component>();
			foreach (Component component in drawing)
			{
				if (component is I2DComponent)
				{
					defer2D.Add(component);
				}
				else
				{
					component.Draw();
				}
			}
			//at last draw 2D
			foreach (Component component in defer2D)
				component.Draw();
		}
		public virtual void Disable()
		{
			Components.Clear();
			Engine.GameScreens.Remove(this);
			if (Engine.DefaultScreen == this)
				Engine.DefaultScreen = Engine.BackgroundScreen;
		}
		public override string ToString()
		{
			return Name;
		}
	}
}